package cn.explink.dop.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.explink.dop.entity.vo.AreaVO;
import cn.explink.dop.entity.vo.OrderVO;
import cn.explink.dop.entity.vo.StorefrontVO;
import cn.explink.dop.enums.BaseInfoEnum;
import cn.explink.dop.enums.DateFormatEnum;
import cn.explink.dop.enums.pub.EnableEnum;
import cn.explink.dop.service.AreaService;
import cn.explink.dop.service.OrderService;
import cn.explink.eap.core.common.model.json.AjaxJson;
import cn.explink.eap.core.util.ResourceUtil;
import cn.explink.eap.web.cgform.controller.autolist.CgAutoListController;
import cn.explink.eap.web.system.pojo.base.TSUser;

/**
 * 基本信息
 *
 * @author firefly 2015-2-5 09:35
 *
 */
@Controller
@RequestMapping("/areaController")
public class AreaController extends CgAutoListController {

	@Autowired
	private AreaService areaService;

	@Autowired
	private OrderService orderService;

	/**
	 * 基本信息
	 *
	 * @param request
	 *            请求
	 * @return 基本信息页面
	 */
	@RequestMapping(params = "index")
	public ModelAndView index(HttpServletRequest request) {
		ModelAndView view = new ModelAndView("dop/area/areaList");
		return view;
	}

	@RequestMapping(params = "create")
	@ResponseBody
	public AjaxJson save(String uid, String baseAreaName, String baseCoordinate, BigDecimal mapcenterLat, BigDecimal mapcenterLng, HttpServletRequest request) {
		String id = null;
		TSUser user = ResourceUtil.getSessionUserName();
		try {
			AreaVO areaVO = new AreaVO();
			areaVO.setBaseAreaName(baseAreaName);
			areaVO.setBaseCoordinate(baseCoordinate);
			areaVO.setBaseDelete(BaseInfoEnum.Used.getValue());
			areaVO.setBaseEnable(BaseInfoEnum.Enable.getValue());
			areaVO.setCreateDate(DateFormatUtils.format(this.orderService.getSysDate(), DateFormatEnum.YMDHMS.getValue()));
			areaVO.setCreateUser(ResourceUtil.getSessionUserName().getId());
			areaVO.setMapcenterLat(mapcenterLat);
			areaVO.setMapcenterLng(mapcenterLng);
			areaVO.setUpdateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(this.orderService.getSysDate()));
			areaVO.setUpdateUser(user.getId());
			areaVO.setUid(uid);
			areaVO.setCreateUser(user.getId());
			id = this.areaService.add(areaVO);
		} catch (Exception e) {
			e.printStackTrace();
		}
		AjaxJson j = new AjaxJson();
		if (null != id) {
			j.setSuccess(true);
		}
		return j;
	}

	@RequestMapping(params = "modifyByUid")
	@ResponseBody
	public AjaxJson modifyByUid(String uid, String baseAreaName, String baseCoordinate, BigDecimal mapcenterLat, BigDecimal mapcenterLng, Integer baseEnable, HttpServletRequest request) {
		try {
			TSUser user = ResourceUtil.getSessionUserName();
			AreaVO areaVO = new AreaVO();
			areaVO.setUid(uid);
			areaVO.setBaseAreaName(baseAreaName);
			areaVO.setBaseCoordinate(baseCoordinate);
			areaVO.setMapcenterLat(mapcenterLat);
			areaVO.setMapcenterLng(mapcenterLng);
			// areaVO.setBaseEnable(baseEnable);
			areaVO.setUpdateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(this.orderService.getSysDate()));
			areaVO.setUpdateUser(user.getId());
			this.areaService.modifyByUid(areaVO);
		} catch (Exception e) {
			e.printStackTrace();
		}
		AjaxJson j = new AjaxJson();
		j.setSuccess(true);
		return j;
	}

	/**
	 *
	 * @param uid
	 * @param baseCoordinate
	 * @param mapcenterLat
	 * @param mapcenterLng
	 * @param request
	 * @return 区域和订单信息
	 */
	@RequestMapping(params = "queryByIdAndOrderStatusList")
	@ResponseBody
	public AjaxJson queryByIdAndOrderStatusList(String id, @RequestParam(value = "orderStatusList[]", required = false) List<Integer> orderStatusList, HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		AjaxJson ajaxJson = new AjaxJson();
		if ((null == id) || (orderStatusList == null) || (orderStatusList.size() == 0)) {
			return ajaxJson;
		}
		try {
			AreaVO areaVO = this.areaService.queryById(id);

			List<OrderVO> orderVOList = this.areaService.getOrderVOListByArea(areaVO, orderStatusList);

			resultMap.put("areaVO", areaVO);
			resultMap.put("orderVOList", orderVOList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		ajaxJson.setAttributes(resultMap);
		return ajaxJson;
	}

	@RequestMapping(params = "queryByRSIdAndOrderStatusList")
	@ResponseBody
	public AjaxJson queryByRSIdAndOrderStatusList(String regionId, String storeId, @RequestParam(value = "orderStatusList[]", required = false) List<Integer> orderStatusList,
			HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		AjaxJson ajaxJson = new AjaxJson();

		try {
			AreaVO areaVO = null;
			if (regionId != null) {
				areaVO = this.areaService.queryById(regionId);
			}

			List<OrderVO> orderVOList = this.areaService.getOrderVOListByIdAndArea(areaVO, orderStatusList, storeId);

			resultMap.put("areaVO", areaVO);
			resultMap.put("orderVOList", orderVOList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		ajaxJson.setAttributes(resultMap);
		return ajaxJson;
	}

	@RequestMapping(params = "modify")
	@ResponseBody
	public AjaxJson updateData(String id, String baseAreaName, String baseCoordinate, HttpServletRequest request) {
		try {
			AreaVO areaVO = new AreaVO();
			areaVO.setId(id);
			areaVO.setBaseAreaName(baseAreaName);
			areaVO.setBaseCoordinate(baseCoordinate);
			areaVO.setUpdateDate(DateFormatUtils.format(new Date(), DateFormatEnum.YMDHMS.getValue()));
			areaVO.setUpdateUser(ResourceUtil.getSessionUserName().getId());
			this.areaService.modify(areaVO);
		} catch (Exception e) {
			e.printStackTrace();
		}
		AjaxJson j = new AjaxJson();
		j.setSuccess(true);
		return j;
	}

	/**
	 * 获取数据
	 *
	 * @param pageNum
	 *            当前页
	 * @param pageSize
	 *            当前页条数
	 * @param request
	 *            请求
	 * @return 结果集
	 */
	@RequestMapping(params = "loadData")
	@ResponseBody
	@SuppressWarnings("unchecked")
	public List<AreaVO> loadData(int pageNum, int pageSize, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			AreaVO vo = new AreaVO();
			vo.setBaseEnable(1);
			map = this.areaService.findVoByPage(vo, pageNum, pageSize);
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<AreaVO> areaVOList = (List<AreaVO>) map.get("list");
		for (AreaVO areaVO : areaVOList) {
			areaVO.setId(areaVO.getId());
		}
		return areaVOList;
	}

	/**
	 * 和地图交互的接口
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "findDataByParam")
	@ResponseBody
	public List<String> findDataByParam(HttpServletRequest request) {
		List<String> pathArr = new ArrayList<String>();
		try {
			int restaurantId = request.getParameter("restaurantId") == null ? 0 : Integer.parseInt(request.getParameter("restaurantId"));
			String userId = request.getParameter("userId") == null ? "" : request.getParameter("userId");
			BigDecimal mapcenterLng = request.getParameter("mapcenterLng") == null ? BigDecimal.ZERO : BigDecimal.valueOf(Double.parseDouble(request.getParameter("mapcenterLng")));
			BigDecimal mapcenterLat = request.getParameter("mapcenterLat") == null ? BigDecimal.ZERO : BigDecimal.valueOf(Double.parseDouble(request.getParameter("mapcenterLat")));
			AreaVO areaVO = new AreaVO();
			areaVO.setCreateUser(userId);
			areaVO.setMapcenterLng(mapcenterLng);
			areaVO.setMapcenterLat(mapcenterLat);
			List<AreaVO> list = this.areaService.getListData(areaVO);

			if ((list != null) && (list.size() > 0)) {
				for (int i = 0; i < list.size(); i++) {
					pathArr.add(list.get(i).getBaseCoordinate());
				}
			}

			return pathArr;
		} catch (NumberFormatException e) {
			e.printStackTrace();
			return pathArr;
		}
	}

	/**
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "findData")
	@ResponseBody
	public List<AreaVO> findData(HttpServletRequest request) {
		try {
			AreaVO vo = new AreaVO();
			vo.setBaseEnable(1);
			List<AreaVO> list = this.areaService.getListData(vo);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return new ArrayList<AreaVO>();
		}
	}

	/**
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "getById")
	@ResponseBody
	public AreaVO getById(String id, HttpServletRequest request) {
		try {
			AreaVO areaVO = this.areaService.queryById(id);
			return areaVO;
		} catch (Exception e) {
			e.printStackTrace();
			return new AreaVO();
		}
	}

	/**
	 * 获取查询数据
	 *
	 * @param pageNum
	 *            当前页
	 * @param pageSize
	 *            当前页条数
	 * @param request
	 *            请求
	 * @return 结果集
	 */
	@RequestMapping(params = "queryList")
	@ResponseBody
	public Map<String, Object> queryData(String baseAreaName, int pageNum, int pageSize, HttpServletRequest request) {
		try {
			AreaVO areaVO = new AreaVO();
			if (StringUtils.isNotBlank(baseAreaName)) {
				areaVO.setBaseAreaName(baseAreaName);
			}
			return this.areaService.findVoByPage(areaVO, pageNum, pageSize);
		} catch (Exception e) {
			e.printStackTrace();
			return new HashMap<String, Object>();
		}
	}

	/**
	 *
	 * @Title: queryByPage
	 * @Description: 分页查询,使用原生SQL
	 * @author 孟凡岭
	 * @param @param baseAreaName
	 * @param @param pageNum
	 * @param @param pageSize
	 * @param @param request
	 * @param @return
	 * @return Map<String,Object> 返回类型
	 * @throws
	 */
	@RequestMapping(params = "queryByPage")
	@ResponseBody
	public Map<String, Object> queryByPage(String baseAreaName, int pageNum, int pageSize, HttpServletRequest request) {
		try {
			AreaVO areaVO = new AreaVO();
			if (StringUtils.isNotBlank(baseAreaName)) {
				areaVO.setBaseAreaName(baseAreaName);
			}
			return this.areaService.getListDataByPage(areaVO, pageNum, pageSize);
		} catch (Exception e) {
			e.printStackTrace();
			return new HashMap<String, Object>();
		}
	}

	/**
	 * 删除数据
	 *
	 * @param rowList
	 *            数据字符串
	 * @param request
	 *            求情
	 * @return 删除状态
	 */
	@RequestMapping(params = "delete")
	@ResponseBody
	public AjaxJson deleteRows(@RequestParam(value = "areaIdList[]", required = false) List<String> areaIdList, HttpServletRequest request) {

		AjaxJson j = new AjaxJson();
		try {
			List<AreaVO> areaVOList = new ArrayList<AreaVO>();
			for (String areaId : areaIdList) {
				AreaVO areaVO = new AreaVO();
				areaVO.setId(areaId);

				areaVOList.add(areaVO);
			}
			if (areaVOList.size() == this.areaService.deleteData(areaVOList)) {
				j.setSuccess(true);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return j;
	}

	/**
	 *
	 * @Title: unEnabled
	 * @Description: 将启用状态改为停用
	 * @author 孟凡岭
	 * @param @param areaIdList
	 * @param @param request
	 * @param @return
	 * @return AjaxJson 返回类型
	 * @throws
	 */
	@RequestMapping(params = "unEnabled")
	@ResponseBody
	public AjaxJson unEnabled(@RequestParam(value = "areaIdList[]", required = false) List<String> areaIdList, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		boolean flag = this.areaService.unEnabled(areaIdList);
		try {
			j.setSuccess(flag);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return j;
	}

	/**
	 *
	 * @Title: enabled
	 * @Description: 将停用状态改为启用
	 * @author 孟凡岭
	 * @param @param areaIdList
	 * @param @param request
	 * @param @return
	 * @return AjaxJson 返回类型
	 * @throws
	 */
	@RequestMapping(params = "enabled")
	@ResponseBody
	public AjaxJson enabled(@RequestParam(value = "areaIdList[]", required = false) List<String> areaIdList, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		boolean flag = this.areaService.enabled(areaIdList);
		try {
			j.setSuccess(flag);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return j;
	}

	/**
	 *
	 * @Title: getAreaByStoreId
	 * @Description: 通过店面ID来查询区域信息，如果不传，则返回启用中的店面关联的区域信息
	 * @author 孟凡岭
	 * @param @param storeId
	 * @param @param request
	 * @param @return
	 * @return List<AreaVO> 返回类型
	 * @throws`
	 */
	@RequestMapping(params = "getAreaByStoreId")
	@ResponseBody
	public AjaxJson getAreaByStoreId(String storeId, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		List<AreaVO> list = new ArrayList<AreaVO>();
		try {
			if (StringUtils.isNotBlank(storeId)) {
				StorefrontVO st = this.areaService.get(StorefrontVO.class, storeId);
				list.addAll(st.getAreaList());
			} else {
				List<StorefrontVO> stoList = this.areaService.findByQueryString("from StorefrontVO where stoStatus=" + EnableEnum.Enable.getValue());
				int listSize = stoList.size();
				for (int i = 0; i < listSize; i++) {
					list.addAll(stoList.get(i).getAreaList());
				}
			}
			/**
			 * 成功返回
			 */
			j.setObj(list);
			j.setSuccess(true);
		} catch (Exception e) {
			// TODO: handle exception
			/**
			 * 出异常返回空数组，success为false
			 */
			e.printStackTrace();
			j.setObj(list);
			j.setSuccess(false);
		}

		return j;
	}
}
